<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
  <!-- 引入样式 -->
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

</head>

<body>
<div id="app">
		<p>
	        <el-input type="text" placeholder="请输入你的名字" v-model="loginName" />
	        
	    </p>
		<p>
			<el-button @click="login()">登录</el-button>
			<el-button @click="close_ws()">关闭</el-button>
			</p>
	    <p>
	        <el-input placeholder="" v-model="message" v-on:keydown.enter.native="sendMessage()"/>
	    </p>
		<el-input ref=textarea type="textarea" v-model="messageList" name="" id="textarea_id" cols="30" rows="10"></el-input>
	</div>

  
  <script>
    new Vue({
		el:'#app',
		data(){
			return{
				ws:null,
				ws_url:'ws://localhost:18082/websocket/chat/',
				loginName:"",
				message:"",
				messageList:""
			}
		},
		methods:{
			login(){
				//debugger
				this.ws = new WebSocket(this.ws_url + this.loginName);
				//ws = new WebSocket("ws://10.2.33.14:8080/websocket");
				// 建立 web socket 连接成功触发事件
				this.ws.onopen = this.onopen;
				// 接收服务端数据时触发事件
				this.ws.onmessage = this.onmessage;
				// 断开 web socket 连接成功触发事件
				this.ws.onclose = this.onclose;
				
				this.ws.onerror = this.onerror;
			},
			sendMessage() {
				if (this.message != '') {
					this.ws.send(this.message);
					this.message ='';
				}
			},
			onopen() {
				this.log_message('Info: WebSocket 连接成功.');
			},
			onmessage (evt) {
				//debugger
				var received_msg = evt.data;
				this.log_message(received_msg);
			},
			onclose () {
				this.log_message('Info: WebSocket 关闭.');
			},
			onerror () {
				this.log_message('Info: WebSocket 出现错误.');
			},
			log_message(msg){
				this.messageList = this.messageList+"\r\n" + msg;
				const textarea = document.getElementById('textarea_id');
				textarea.scrollTop = textarea.scrollHeight;
			},
			close_ws(){
				//debugger
				alert("close");
				this.ws.close();
			}
		},
		created() {
			console.log("created");
		},
		mounted() {
			console.log("mounted start");
		}
	});
		
</script>
</body>